<template>
  <el-card shadow="navar">
    <el-row :gutter="15">
      <el-col :span="8">
        <MmvPeerComponent
          :peerData="formData"
          :activitySeckillList="formData.activitySeckillList"
        ></MmvPeerComponent>
      </el-col>
      <el-col :span="16">
        <el-row :gutter="15">
          <el-form
            ref="elForm"
            :model="formData"
            :rules="rules"
            size="medium"
            label-width="130px"
          >
            <el-col :span="24">
              <el-form-item label="活动名称" prop="peerTitle">
                <el-input
                  v-model.trim="formData.peerTitle"
                  placeholder="请输入活动名称"
                  :maxlength="50"
                  show-word-limit
                  clearable
                  :style="{ width: '100%' }"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="活动开始时间" prop="timeStart">
                <el-date-picker
                  v-model.trim="formData.timeStart"
                  type="datetime"
                  placeholder="请选择开始时间"
                  :style="{ width: '100%' }"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="pickerOptionsStart"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="活动结束时间" prop="timeEnd">
                <el-date-picker
                  v-model.trim="formData.timeEnd"
                  type="datetime"
                  placeholder="请选择结束时间"
                  :style="{ width: '100%' }"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  :picker-options="pickerOptionsEnd"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="虚拟报名人数量" prop="inventedJoinNumber">
                <el-input
                  v-model.number="formData.inventedJoinNumber"
                  placeholder="请输入报名人数"
                  clearable
                  :style="{ width: '100%' }"
                >
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="邀请设置" prop="invite">
                <el-radio-group v-model="formData.invite">
                  <el-radio
                    v-for="item in dict.type.activity_invite"
                    :key="item.value"
                    :label="parseInt(item.value)"
                    >{{ item.label }}</el-radio
                  >
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="活动门店/部门" prop="applicableUnitNo">
                <el-select
                  v-model="formData.applicableUnitNo"
                  @change="applicableUnitNoChange"
                  multiple
                  placeholder="请选择活动门店/部门"
                  clearable
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="item in applicableUnitOptions"
                    :key="item.applicableUnitNo"
                    :label="item.applicableUnit"
                    :value="item.applicableUnitNo"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <MmvAddGoods
                title="添加同行活动商品"
                ref="addDialog"
                @cancel="isShowAddGoods = false"
                @submit="onGoodsSubmit"
              ></MmvAddGoods>
              <el-divider></el-divider>
              <el-form-item label="添加同行商品" prop="activitySeckillList">
                <el-button type="primary" icon="el-icon-plus" @click="addGoods"
                  >添加商品</el-button
                >
                <span :style="{ color: '#606266', marginLeft: '15px' }"
                  >最多支持设置5级阶梯礼包,组队人数建议2～10人，最少2人以上</span
                >
                <el-table
                  style="margin-top: 10px"
                  :data="formData.activitySeckillList"
                >
                  <el-table-column label="类型" align="center" prop="peerType">
                    <template slot-scope="scope">
                      {{
                        scope.row.peerType
                          | typeFilter(dict.type.activity_goodsType)
                      }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="实物照片"
                    align="center"
                    prop="peerUrl"
                  >
                    <template slot-scope="scope">
                      <div v-if="scope.row.peerUrl != ''">
                        <el-image
                          style="width: 48px; height: 48px"
                          :src="getImgUrl(scope.row.peerUrl)"
                          fit="cover"
                        ></el-image>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="奖品名称"
                    align="center"
                    prop="peerName"
                  ></el-table-column>
                  <el-table-column
                    label="组队人数"
                    align="center"
                    prop="peerNumber"
                  ></el-table-column>
                  <el-table-column
                    label="赠送人数"
                    align="center"
                    prop="peerGive"
                  ></el-table-column>
                  <el-table-column
                    label="奖品库存"
                    align="center"
                    prop="peerStock"
                  ></el-table-column>
                  <el-table-column
                    label="操作"
                    min-width="200px"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button
                      >
                      <el-button
                        size="mini"
                        type="danger"
                        @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
              <el-divider></el-divider>
            </el-col>
            <el-col :span="24">
              <el-form-item label="活动封面" prop="coverImage" required>
                <MmvUploadImage @upImg="upcoverImage" ref="coverImage">
                  <el-button size="small" type="primary" icon="el-icon-upload"
                    >添加图片</el-button
                  >
                  <div slot="tip" class="el-upload__tip">
                    支持JPG/JPEG/PNG，尺寸375px*256px，不超过2M，仅限1张图片
                  </div>
                </MmvUploadImage>
              </el-form-item>
              <el-form-item label="详情封面" prop="detailImage" required>
                <MmvUploadImage
                  @upImg="updetailImage"
                  :more="true"
                  size="2"
                  ref="detailImage"
                >
                  <el-button size="small" type="primary" icon="el-icon-upload"
                    >添加图片</el-button
                  >
                  <div slot="tip" class="el-upload__tip">
                    支持JPG/JPEG/PNG，尺寸375px*256px，不超过2M，可选多张图片
                  </div>
                </MmvUploadImage>
              </el-form-item>
              <el-form-item label="分享封面" prop="shareImage" required>
                <MmvUploadImage @upImg="upshareImage" ref="shareImage">
                  <el-button size="small" type="primary" icon="el-icon-upload"
                    >添加图片</el-button
                  >
                  <div slot="tip" class="el-upload__tip">
                    支持JPG/JPEG/PNG，尺寸375px*256px，不超过2M，仅限1张图片
                  </div>
                </MmvUploadImage>
              </el-form-item>
              <el-form-item label="活动描述" prop="peerContent">
                <editor v-model="formData.peerContent" :min-height="192" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item size="large">
                <el-button @click="goBack">取消</el-button>
                <el-button type="primary" @click="submitForm" v-onceClick
                  >提交</el-button
                >
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </el-col>
    </el-row>
  </el-card>
</template>

<script>
import { addPeer, getPeerById } from '@/api/activity/peer'
import { applicableUnitList } from '@/api/coupon/manage'
import MmvUploadImage from '../../components/mmv-upload-image.vue'
import MmvAddGoods from '../../components/mmv-add-peer.vue'
import MmvPeerComponent from '../../components/activity-mobile/mmv-peer-component.vue'
export default {
  components: {
    MmvUploadImage,
    MmvAddGoods,
    MmvPeerComponent,
  },
  dicts: ['activity_invite', 'activity_goodsType'],
  data() {
    // 验证开始时间的规则
    var checkTimeStart = (rule, value, callback) => {
      if (this.formData.timeEnd != '' && value > this.formData.timeEnd) {
        callback(new Error('活动开始时间需小于活动结束时间'))
      }
      if (
        this.formData.timeStart &&
        this.formData.timeEnd &&
        this.formData.timeStart != '' &&
        this.formData.timeEnd != ''
      ) {
        this.$refs['elForm'].clearValidate('timeEnd')
      }
      return callback()
    }
    // 验证结束时间的规则
    var checkTimeEnd = (rule, value, callback) => {
      if (
        this.formData.timeEnd != '' &&
        this.formData.timeStart != '' &&
        value < this.formData.timeStart
      ) {
        callback(new Error('活动结束时间需大于活动开始时间'))
      }
      if (
        this.formData.timeStart &&
        this.formData.timeEnd &&
        this.formData.timeStart != '' &&
        this.formData.timeEnd != ''
      ) {
        this.$refs['elForm'].clearValidate('timeStart')
      }
      return callback()
    }
    return {
      // 开始结束日期限制
      pickerOptionsStart: {
        disabledDate: (time) => {
          if (this.formData.timeEnd) {
            return time.getTime() >= new Date(this.formData.timeEnd).getTime()
          }
        },
      },
      // 结束日期限制
      pickerOptionsEnd: {
        disabledDate: (time) => {
          if (this.formData.timeStart) {
            return time.getTime() <= new Date(this.formData.timeStart).getTime()
          }
        },
      },
      isShowAddGoods: false,
      //门店数据
      applicableUnitOptions: [],
      //表单数据
      formData: {
        peerTitle: '',
        timeStart: '',
        timeEnd: '',
        inventedJoinNumber: null,
        invite: 1,
        coverImage: '',
        detailImage: '',
        shareImage: '',
        activitySeckillList: [],
        applicableUnitNo: [],
      },
      //表单验证
      rules: {
        peerTitle: [
          {
            required: true,
            message: '请输入活动名称',
            trigger: 'blur',
          },
        ],
        timeStart: [
          {
            required: true,
            message: '请输入活动开始时间',
            trigger: 'change',
          },
          { validator: checkTimeStart, trigger: 'change' },
        ],
        timeEnd: [
          {
            required: false,
            message: '请输入活动结束时间',
            trigger: 'change',
          },
          { validator: checkTimeEnd, trigger: 'change' },
        ],
        inventedJoinNumber: [
          {
            required: true,
            message: '请输入虚拟报名人数量',
            trigger: 'blur',
          },
          {
            pattern: /^([1-9]\d*)$/,
            message: '只能输入正整数',
            trigger: 'blur',
          },
        ],
        invite: [
          {
            required: true,
            message: '请选择邀请设置',
            trigger: 'change',
          },
        ],
        applicableUnitNo: [
          {
            required: true,
            message: '请选择活动门店/部门',
            trigger: 'change',
          },
        ],
        activitySeckillList: [
          {
            required: true,
            message: '请录入商品',
            trigger: 'blur',
          },
        ],
        coverImage: [
          {
            required: true,
            message: '请选择活动封面',
            trigger: 'blur',
          },
        ],
        detailImage: [
          {
            required: true,
            message: '请选择详情封面',
            trigger: 'blur',
          },
        ],
        shareImage: [
          {
            required: true,
            message: '请选择分享封面',
            trigger: 'blur',
          },
        ],
        peerContent: [
          {
            required: true,
            message: '请输入活动描述',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  filters: {
    typeFilter(val, type) {
      if (val === null) return null
      let data = type.filter((item) => {
        return val == item.value
      })
      if (data.length) {
        return data[0].label
      } else {
        return val
      }
    },
  },
  created() {
    Promise.all([this.getApplicableUnitList()]).then(([res]) => {
      if (this.$route.params.id) {
        this.$nextTick(() => {
          this.getPeerDetail()
        })
      }
    })
  },
  methods: {
    // 获取同行活动详情
    getPeerDetail() {
      getPeerById({ id: this.$route.params.id }).then((res) => {
        this.formData = res.data
        this.formData.applicableUnitNo = res.data.activityUnit.map((item) => {
          return item.applicableUnitNo
        })
        this.$refs.coverImage.previewToUrl(res.data.coverImage)
        this.$refs.detailImage.previewToUrl(res.data.detailImage)
        this.$refs.shareImage.previewToUrl(res.data.shareImage)
      })
    },
    // 获取活动门店
    getApplicableUnitList() {
      applicableUnitList().then((res) => {
        this.applicableUnitOptions = res.data
      })
    },
    // 活动门店变化
    applicableUnitNoChange(val) {
      this.formData.activityUnit = val.map((item) => {
        return this.applicableUnitOptions.filter((e) => {
          return e.applicableUnitNo === item
        })[0]
      })
      this.$forceUpdate()
    },
    // 弹窗事件
    addGoods() {
      if (this.formData.activitySeckillList.length >= 5) {
        this.$message.warning('最多添加5条数据，若要添加数据，请先删除1条数据')
      } else {
        this.$refs.addDialog.show({ type: null })
      }
    },
    // 添加商品
    onGoodsSubmit(goods) {
      if (goods.index !== null) {
        this.formData.activitySeckillList.splice(goods.index, 1, goods.row)
      } else {
        this.formData.activitySeckillList.push(goods.row)
      }
    },
    // 删除商品
    handleDelete(index) {
      this.formData.activitySeckillList.splice(index, 1)
    },
    // 编辑商品
    handleEdit(index, row) {
      if (index === null) {
        this.$refs.addDialog.show()
      } else {
        this.$refs.addDialog.show({
          type: index,
          row: this.deepClone(row),
        })
      }
    },
    upcoverImage(url) {
      // 活动封面上传成功地址
      this.formData.coverImage = url[0]
      this.$refs['elForm'].validateField('coverImage')
    },
    updetailImage(url) {
      // 详情封面上传成功地址
      this.formData.detailImage = url.join(',')
      this.$refs['elForm'].validateField('detailImage')
    },
    upshareImage(url) {
      // 分享封面上传成功地址
      this.formData.shareImage = url[0]
      this.$refs['elForm'].validateField('shareImage')
    },
    submitForm() {
      this.$refs['elForm'].validate((valid) => {
        if (!valid) {
          this.$message.error('验证不通过，请检查输入')
          return
        } else {
          if (
            this.$route.params.type === 'copy' ||
            this.$route.params.type === 'add'
          ) {
            delete this.formData.id
          }
          addPeer(this.formData).then((res) => {
            this.$message.success(res.msg)
            this.goBack()
          })
        }
      })
    },
    goBack() {
      this.$router.go(-1) // 返回
      //关闭子页面
      this.$store.state.tagsView.visitedViews.splice(
        this.$store.state.tagsView.visitedViews.findIndex(
          (item) => item.path === this.$route.path
        ),
        1
      )
      this.$router.push(
        this.$store.state.tagsView.visitedViews[
          this.$store.state.tagsView.visitedViews.length - 1
        ].path
      )
    },
  },
}
</script>
<style scoped>
.img {
  height: 300px;
  border: 1px solid #ccc;
  display: block;
  border-radius: 5px;
  margin-bottom: 15px;
}
</style>